package com.bckj.freshnow.order.trade.ons.listener;


import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.bckj.fastboot.mq.ons.OnsConsumeStrategy;
import com.bckj.fastboot.mq.ons.OnsListener;
import com.bckj.freshnow.common.constant.TradeOrderMQConstants;
import com.bckj.freshnow.order.trade.ons.listener.strategy.TradeOrderConsumeStrategyFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
@OnsListener(topic = TradeOrderMQConstants.TOPIC)
public class TradeOrderListener implements MessageListener {

    private final TradeOrderConsumeStrategyFactory tradeOrderConsumeStrategyFactory;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        String body = new String(message.getBody());
        log.info("消息内容：{}", body);
        OnsConsumeStrategy onsConsumeStrategy = tradeOrderConsumeStrategyFactory.getOnsConsumeStrategy(message.getTag());
        if (onsConsumeStrategy == null) {
            return Action.CommitMessage;
        }
        try {
            onsConsumeStrategy.consume(body);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }
}
